﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using iWare.Wms.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Transactions;
using Yitter.IdGenerator;

namespace iWare.Wms.Application.PDA
{
    /// <summary>
    /// 临时库位服务
    /// </summary>
    [Route("api/TemporaryLocation")]
    [ApiDescriptionSettings("PDA", Name = "TemporaryLocation", Order = 1)]

    public class TemporaryLocationServices : IDynamicApiController, ITransient
    {
        private readonly ERPService _erpService; //ERP服务
        private readonly IRepository<WareArea, MasterDbContextLocator> _wareAreaRep; //库区仓储
        private readonly IRepository<WareMaterial, MasterDbContextLocator> _wareMaterialRep; //物料仓储
        private readonly IRepository<WareContainer, MasterDbContextLocator> _wareContainerRep; //容器仓储
        private readonly IRepository<WareContainerVsMaterial, MasterDbContextLocator> _wareContainerVsMaterialRep; //容器与物料关系仓储
        private readonly IRepository<WareLocation, MasterDbContextLocator> _wareLocationRep; //库位仓储
        private readonly IRepository<WareLocationVsContainer, MasterDbContextLocator> _wareLocationVsContainerRep; //库位与容器关系仓储
        private readonly IRepository<WareTask, MasterDbContextLocator> _wareTaskRep; //任务仓储
        private readonly IRepository<WareStock, MasterDbContextLocator> _wareStockRep; //库存仓储
        private readonly IRepository<GoodsDeliveryDetails, MasterDbContextLocator> _goodsDeliveryDetailsRep; //送货单详情仓储
        private readonly IRepository<GoodsDelivery, MasterDbContextLocator> _goodsDeliveryRep; //送货单仓储
        private readonly IRepository<CollectDeliveryDetails, MasterDbContextLocator> _collectDeliveryDetailsRep; //收货明细仓储
        private readonly IRepository<WareOrderDetails, MasterDbContextLocator> _wareOrderDetailsRep; //单据仓储
        private readonly IRepository<v_materialtag_project, MasterDbContextLocator> _vMaterialtagProjectRep; //物料与项目试图仓储

        #region 默认
        /// <summary>
        /// 默认
        /// </summary>
        /// <param name="erpService"></param>
        /// <param name="wareAreaRep"></param>
        /// <param name="wareMaterialRep"></param>
        /// <param name="wareContainerRep"></param>
        /// <param name="wareContainerVsMaterialRep"></param>
        /// <param name="wareLocationRep"></param>
        /// <param name="wareLocationVsContainerRep"></param>
        /// <param name="wareTaskRep"></param>
        /// <param name="wareStockRep"></param>
        /// <param name="goodsDeliveryDetailsRep"></param>
        /// <param name="goodsDeliveryRep"></param>
        /// <param name="collectDeliveryDetailsRep"></param>
        /// <param name="wareOrderDetailsRep"></param>
        /// <param name="vMaterialtagProjectRep"></param>
        public TemporaryLocationServices(
            ERPService erpService,
            IRepository<WareArea, MasterDbContextLocator> wareAreaRep,
            IRepository<WareMaterial, MasterDbContextLocator> wareMaterialRep,
            IRepository<WareContainer, MasterDbContextLocator> wareContainerRep,
            IRepository<WareContainerVsMaterial, MasterDbContextLocator> wareContainerVsMaterialRep,
            IRepository<WareLocation, MasterDbContextLocator> wareLocationRep,
            IRepository<WareLocationVsContainer, MasterDbContextLocator> wareLocationVsContainerRep,
            IRepository<WareTask, MasterDbContextLocator> wareTaskRep,
            IRepository<WareStock, MasterDbContextLocator> wareStockRep,
            IRepository<GoodsDeliveryDetails, MasterDbContextLocator> goodsDeliveryDetailsRep,
            IRepository<GoodsDelivery, MasterDbContextLocator> goodsDeliveryRep,
            IRepository<CollectDeliveryDetails, MasterDbContextLocator> collectDeliveryDetailsRep,
            IRepository<WareOrderDetails, MasterDbContextLocator> wareOrderDetailsRep,
            IRepository<v_materialtag_project, MasterDbContextLocator> vMaterialtagProjectRep
        )
        {
            _erpService = erpService;
            _wareAreaRep = wareAreaRep;
            _wareMaterialRep = wareMaterialRep;
            _wareContainerRep = wareContainerRep;
            _wareContainerVsMaterialRep = wareContainerVsMaterialRep;
            _wareLocationRep = wareLocationRep;
            _wareLocationVsContainerRep = wareLocationVsContainerRep;
            _wareTaskRep = wareTaskRep;
            _wareStockRep = wareStockRep;
            _goodsDeliveryDetailsRep = goodsDeliveryDetailsRep;
            _goodsDeliveryRep = goodsDeliveryRep;
            _collectDeliveryDetailsRep = collectDeliveryDetailsRep;
            _wareOrderDetailsRep = wareOrderDetailsRep;
            _vMaterialtagProjectRep = vMaterialtagProjectRep;
        }
        #endregion

        /// <summary>
        /// 扫描物料二维码----临时库位入库使用
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetMaterial")]
        public async Task<WareContainerVsMaterialInput> GetMaterialByIn([FromBody] TemporaryInInput input)
        {
            //var goodsDeliveryDetails = await _goodsDeliveryDetailsRep.FirstOrDefaultAsync(z => z.ProjectCode == input.ProjectCode && z.Code == input.Code
            //&& z.GoodsDelivery.DeliveryNo == input.DeliveryNo);

            // 查询物料基础信息
            var wareMaterial = await _wareMaterialRep.FirstOrDefaultAsync(z => z.Code == input.Code);
            if (wareMaterial == null)
            {
                //// 查询物料的检验方式
                //var erpService = await _erpService.SelectMaterial(input.Code, input.SpecificationModel);

                // 添加物料基础信息
                var modeld = new WareMaterial()
                {
                    Code = input.Code,
                    Name = input.Name,
                    SpecificationModel = input.SpecificationModel,
                    //Unit = goodsDeliveryDetails.Unit,
                    InspectionMethod = input.InspectionMethod,
                    Quantity = 1,//goodsDeliveryDetails.DeliveryQuantity,
                    //BrandName = goodsDeliveryDetails.BrandName,
                    //SupplerCode = goodsDeliveryDetails.SupplierInfoCode
                };
                await _wareMaterialRep.InsertAsync(modeld);

                wareMaterial.Id = modeld.Id;
            }

            //if (goodsDeliveryDetails == null)
            //{
            var model = wareMaterial.Adapt<WareContainerVsMaterialInput>();
            model.ProjectCode = input.ProjectCode;
            model.MaterialId = wareMaterial.Id;
            model.DeliveryNo = "N/A";
            model.BindQuantity = 1;
            return model;
            //}
            //else
            //{
            //    var model = goodsDeliveryDetails.Adapt<WareContainerVsMaterialInput>();
            //    model.MaterialId = wareMaterial.Id;
            //    model.BindQuantity = goodsDeliveryDetails.DeliveryQuantity;
            //    return model;
            //}
        }

        /// <summary>
        /// 2023/4/24 --- 仓库收货查询送货单号
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("QueryCollectModel")]
        public async Task QueryCollectModel([FromQuery] CollectcxInput input)
        {
            //查询送货单信息
            var goodsDelivery = await _goodsDeliveryRep.FirstOrDefaultAsync(z => z.DeliveryNo == input.DeliveryNo);
            if (goodsDelivery == null) throw Oops.Oh("送货单号不存在!");

            //if (goodsDelivery != null && goodsDelivery.Status == AuditStatusEnum.yuyuezhong) throw Oops.Oh("送货单号预约中，不能进行入库!");
            //if (goodsDelivery != null && goodsDelivery.Status == AuditStatusEnum.yuyuechenggong) throw Oops.Oh("送货单号预约成功，不能进行入库!");
            //if (goodsDelivery != null && goodsDelivery.Status == AuditStatusEnum.shenhezhong) throw Oops.Oh("送货单号审核中，不能进行入库!");
            //if (goodsDelivery != null && goodsDelivery.Status == AuditStatusEnum.bohui) throw Oops.Oh("送货单号驳回，不能进行入库!");

            //检查收货表物料信息
            var collectModel = await _collectDeliveryDetailsRep.FirstOrDefaultAsync(p => p.CollectDelivery.DeliveryNo == input.DeliveryNo);
            if (collectModel == null) throw Oops.Oh("该送货单号无收货信息");
        }

        /// <summary>
        /// 2023/4/24 (新)扫描物料二维码----临时库位入库使用
        /// </summary>
        /// <returns></returns>
        [HttpPost("NewGetMaterial")]
        public async Task<WareContainerVsMaterialInput> NewGetMaterialByIn([FromBody] TemporaryInInput input)
        {
            //判断是否是该收货单物料
            if (!string.IsNullOrEmpty(input.DeliveryNo))
            {

                //查询该送货单的收货信息
                var collectModel = await _collectDeliveryDetailsRep.Where(p => p.CollectDelivery.DeliveryNo == input.DeliveryNo && p.Name == input.Name
                && p.SpecificationModel == input.SpecificationModel && p.Code == input.Code && p.InspectionMethod == input.InspectionMethod && p.CollectDelivery.DeliveryNo == input.DeliveryNo)
                .FirstOrDefaultAsync();

                if (collectModel == null) throw Oops.Oh("收货单无此物料信息");

                // 查询物料基础信息
                var wareMaterial = await _wareMaterialRep.FirstOrDefaultAsync(z => z.Code == input.Code
                && z.Name == input.Name && z.SpecificationModel == input.SpecificationModel);

                if (wareMaterial == null)
                {
                    // 添加物料基础信息
                    var modeld = new WareMaterial()
                    {
                        Code = input.Code,
                        Name = input.Name,
                        SpecificationModel = input.SpecificationModel,
                        Unit = collectModel.Unit,
                        InspectionMethod = input.InspectionMethod,
                        Quantity = collectModel.CollectQuantity,
                        BrandName = collectModel.BrandName,
                        SupplerCode = collectModel.SupplierInfoCode,
                    };
                    await _wareMaterialRep.InsertAsync(modeld);

                    wareMaterial.Id = modeld.Id;
                }

                var hegeQuatity = new decimal(1.00); // 定义合格数

                // 物料检验方式是免检，直接显示收货数量
                if (collectModel.InspectionMethod == InspectionMethodEnum.mianjian)
                    hegeQuatity = collectModel.CollectQuantity;
                // 质检后质检结果是合格或者让步接收，合格数直接显示质检数量
                else if (collectModel.IsQuality == YesOrNot.Y && collectModel.QualityResult == QualityEnum.HeGe || collectModel.QualityResult == QualityEnum.RangBu)
                    hegeQuatity = collectModel.CollectQuantity;//合格数量
                else
                    hegeQuatity = collectModel.CollectQuantity - collectModel.QualityNumber; //合格数量

                var model = collectModel.Adapt<WareContainerVsMaterialInput>();
                model.MaterialId = wareMaterial.Id;
                model.BindQuantity = hegeQuatity;

                return model;
            }
            else
            {
                //查询收货详情信息
                var collectModelDetails = await _collectDeliveryDetailsRep.FirstOrDefaultAsync(z => z.Name == input.Name
                && z.Code == input.Code && z.SpecificationModel == input.SpecificationModel);

                //判断收货详情是否存在该物料
                if (collectModelDetails != null)
                {
                    // 查询物料基础信息
                    var wareMaterial = await _wareMaterialRep.FirstOrDefaultAsync(z => z.Code == input.Code
                    && z.Name == input.Name && z.SpecificationModel == input.SpecificationModel);

                    if (wareMaterial == null)
                    {
                        // 添加物料基础信息
                        var modeld = new WareMaterial()
                        {
                            Code = input.Code,
                            Name = input.Name,
                            SpecificationModel = input.SpecificationModel,
                            Unit = collectModelDetails.Unit,
                            InspectionMethod = input.InspectionMethod,
                            Quantity = collectModelDetails.CollectQuantity,
                            BrandName = collectModelDetails.BrandName,
                            SupplerCode = collectModelDetails.SupplierInfoCode,
                        };
                        await _wareMaterialRep.InsertAsync(modeld);

                        wareMaterial.Id = modeld.Id;
                    }

                    var hegeQuatity = new decimal(1.00); // 定义合格数

                    var model = collectModelDetails.Adapt<WareContainerVsMaterialInput>();
                    model.MaterialId = wareMaterial.Id;
                    model.BindQuantity = hegeQuatity;

                    return model;
                }
                else
                {
                    // 查询物料基础信息
                    var wareMaterial = await _wareMaterialRep.FirstOrDefaultAsync(p => p.Code == input.Code && p.SpecificationModel == input.SpecificationModel && p.Name == input.Name);
                    if (wareMaterial == null) throw Oops.Oh("无此物料信息");

                    // 查询物料标签试图信息
                    var vMaterialtagProjectModel = await _vMaterialtagProjectRep.DetachedEntities
                        .Where(p => p.Code == input.Code && p.SpecificationModel == input.SpecificationModel && p.Name == input.Name).FirstOrDefaultAsync();
                    collectModelDetails.ProjectCode = vMaterialtagProjectModel.ProjectCode;

                    var model = wareMaterial.Adapt<WareContainerVsMaterialInput>();
                    model.SpecificationModel = wareMaterial.SpecificationModel;
                    model.InspectionMethod = wareMaterial.InspectionMethod;
                    model.Unit = wareMaterial.Unit;
                    model.MaterialId = wareMaterial.Id;
                    model.DeliveryNo = input.DeliveryNo;
                    model.DeliveryNo = "N/A";
                    model.BindQuantity = 1;

                    return model;
                }
            }
        }

        /// <summary>
        /// 选择库区----临时库位出库使用
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetLocationByOut")]
        public async Task<List<TemporaryOutOutput>> GetLocationByOut([FromBody] TemporaryOutInput input)
        {
            var locationCodes = await _wareLocationRep.DetachedEntities.Where(z => z.AreaID == input.AreaID && z.LocationStatus == LocationStatusEnum.cunhuo)
                .Select(z => z.Code).Distinct().ToListAsync();

            var wareStockList = await _wareStockRep.DetachedEntities.Where(z => locationCodes.Contains(z.LocationCode)
              && z.CurrentQuantity > new decimal(0.00)).ToListAsync();

            // 根据库位编号和容器编号去重
            var wareStockDistinct = wareStockList.Select(t => new
            {
                t.LocationCode,
                t.ContainerCode
            }).Distinct();

            var list = new List<TemporaryOutOutput>();
            foreach (var item in wareStockDistinct)
            {
                var model = item.Adapt<TemporaryOutOutput>();
                model.CurrentQuantity = wareStockList.Where(z => z.LocationCode == item.LocationCode && z.ContainerCode == item.ContainerCode).Sum(z => z.CurrentQuantity);

                list.Add(model);
            }

            return list;
        }

        /// <summary>
        /// 扫描物料二维码----临时库位出库使用
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetMaterialByOut")]
        public async Task<List<TemporaryOutOutput>> GetMaterialByOut([FromBody] TemporaryOutInput input)
        {
            var locationCodes = await _wareLocationRep.DetachedEntities.Where(z => z.AreaID == input.AreaID && z.LocationStatus == LocationStatusEnum.cunhuo)
                .Select(z => z.Code).Distinct().ToListAsync();

            var wareStock = await _wareStockRep.DetachedEntities.Where(z => locationCodes.Contains(z.LocationCode)
                && z.Code == input.Code).ToListAsync();

            return wareStock.Adapt<List<TemporaryOutOutput>>();
        }

        /// <summary>
        /// 临时库位入库
        /// </summary>
        /// <returns></returns>
        [HttpPost("TemporaryLocationIn")]
        public async Task TemporaryLocationIn([FromBody] TemporaryInOutput input)
        {
            if (input.newWareContainerVsMaterials.Count == 0) throw Oops.Oh("无入库物料");

            // 根据所属库区ID查询库区信息
            var wareArea = await _wareAreaRep.FirstOrDefaultAsync(z => z.Id == input.AreaID);
            if (wareArea == null) throw Oops.Oh("所属库区信息不存在!");

            using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }, TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    //查询一条空闲的库位信息
                    var wareLocation = await _wareLocationRep.Where(z => z.AreaID == input.AreaID && z.LocationStatus == LocationStatusEnum.kongxian).FirstOrDefaultAsync();
                    if (wareLocation == null) throw Oops.Oh("该库区暂无空闲库位");

                    //查询一条空闲的库位信息
                    var wareContainer = await _wareContainerRep.Where(z => z.AreaID == input.AreaID && z.ContainerStatus == ContainerStatusEnum.kongxian).FirstOrDefaultAsync();
                    if (wareContainer == null) throw Oops.Oh("该库区暂无空闲容器");

                    //判断是否在任务中
                    var isExit = await _wareTaskRep.AnyAsync(n => n.TaskStatus != TaskStatusEnum.Complete && n.ContainerCode == wareContainer.Code);
                    if (isExit) throw Oops.Oh("容器存在未完成任务!");

                    //组盘单据
                    var orderNo = YitIdHelper.NextId().ToString();

                    //进行组盘
                    foreach (var itemsub in input.newWareContainerVsMaterials)
                    {
                        var model = itemsub.Adapt<WareContainerVsMaterial>();
                        model.Id = YitIdHelper.NextId();
                        model.OrderNo = orderNo;
                        model.ContainerCode = wareContainer.Code;
                        model.ContainerId = wareContainer.Id;
                        model.ContainerVsMaterialStatus = CommonStatus.ENABLE;
                        await _wareContainerVsMaterialRep.InsertAsync(model);

                        //更新库存
                        var stockDetailModel = await _wareStockRep.FirstOrDefaultAsync(n => n.ContainerCode == wareContainer.Code
                        && n.ProjectCode == itemsub.ProjectCode && n.Code == itemsub.Code && n.SpecificationModel == itemsub.SpecificationModel);
                        if (stockDetailModel != null)
                        {
                            stockDetailModel.StockQuantity += itemsub.BindQuantity;
                            await _wareStockRep.UpdateAsync(stockDetailModel);
                        }
                        else
                        {
                            stockDetailModel = new WareStock()
                            {
                                ProjectCode = itemsub.ProjectCode,
                                Code = itemsub.Code,
                                Name = itemsub.Name,
                                SpecificationModel = itemsub.SpecificationModel,
                                Unit = itemsub.Unit,
                                StockQuantity = itemsub.BindQuantity,
                                CurrentQuantity = itemsub.BindQuantity,
                                ContainerCode = wareContainer.Code,
                                LocationCode = wareLocation.Code,
                                XuHao = itemsub.XuHao,
                                BrandName = itemsub.BrandName,
                                ExpirationTime = DateTimeOffset.Now,
                                CreatedUserId = CurrentUserInfo.UserId,
                                CreatedUserName = CurrentUserInfo.Name,
                                CreatedTime = DateTimeOffset.Now,
                                UpdatedUserId = CurrentUserInfo.UserId,
                                UpdatedUserName = CurrentUserInfo.Name,
                                UpdatedTime = DateTimeOffset.Now
                            };
                            await _wareStockRep.InsertAsync(stockDetailModel);
                        }
                    }

                    //新增库位容器关系表
                    var newWareLocationVsContainerModel = new WareLocationVsContainer()
                    {
                        LocationId = wareLocation.Id,
                        LocationCode = wareLocation.Code,
                        ContainerId = wareContainer.Id,
                        ContainerCode = wareContainer.Code,
                        LocationVsContainerStatus = CommonStatus.ENABLE
                    };
                    await _wareLocationVsContainerRep.InsertAsync(newWareLocationVsContainerModel);

                    //更新库位状态
                    wareLocation.LocationStatus = LocationStatusEnum.cunhuo;
                    await _wareLocationRep.UpdateAsync(wareLocation);

                    //更新容器状态
                    wareContainer.ContainerStatus = ContainerStatusEnum.kuwei;
                    await _wareContainerRep.UpdateAsync(wareContainer);

                    //创建任务
                    var taskModel = new WareTask()
                    {
                        OrderNo = orderNo,
                        TaskNo = YitIdHelper.NextId().ToString(),
                        TaskStatus = TaskStatusEnum.Complete,
                        TaskModel = TaskModel.SHOUDONG,
                        TaskType = TaskType.In,
                        TaskName = TaskNameConst.TemporaryLocation_ManualIn,
                        Priority = 1,
                        ContainerCode = wareContainer.Code,
                        FromLocationCode = "N/A", //入库口
                        ToLocationCode = wareLocation.Code,
                        UpdatedUserId = CurrentUserInfo.UserId,
                        UpdatedUserName = CurrentUserInfo.Name,
                        UpdatedTime = DateTimeOffset.Now
                    };
                    await _wareTaskRep.InsertAsync(taskModel);

                    // 提交事务
                    scope.Complete();
                }
                catch (Exception ex)
                {
                    throw Oops.Oh("[TemporaryLocationIn]临时入库异常：" + ex.StackTrace + "," + ex.Message);
                }
                finally
                {
                    scope.Dispose();
                }
            }
        }

        /// <summary>
        /// 临时库位出库
        /// </summary>
        /// <returns></returns>
        [HttpPost("TemporaryLocationOut")]
        public async Task TemporaryLocationOut([FromBody] List<TemporaryOutOutput> input)
        {
            if (input is null || input.Count <= 0) throw Oops.Oh("无出库的库位信息");

            using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }, TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    foreach (var item in input)
                    {
                        //检查托盘
                        var wareContainer = await _wareContainerRep.FirstOrDefaultAsync(n => n.Code == item.ContainerCode);
                        if (wareContainer == null) throw Oops.Oh("容器信息不存在!");
                        if (wareContainer.ContainerStatus != ContainerStatusEnum.kuwei) continue;

                        //检查库位
                        var locationModel = await _wareLocationRep.FirstOrDefaultAsync(p => p.Code == item.LocationCode && p.LocationStatus == LocationStatusEnum.cunhuo);
                        if (wareContainer == null) throw Oops.Oh("库位不存在！");

                        //检查库位与容器关系
                        var wareLocationVsContainer = await _wareLocationVsContainerRep.FirstOrDefaultAsync(
                            n => n.ContainerCode == item.ContainerCode && n.LocationCode == item.LocationCode && n.LocationVsContainerStatus == CommonStatus.ENABLE);
                        if (wareLocationVsContainer == null) throw Oops.Oh("托盘库位关系不存在！");

                        //检查容器与物料关系
                        var wareContainerVsMaterialList = await _wareContainerVsMaterialRep.DetachedEntities.Where(p => p.ContainerCode == item.ContainerCode
                            && p.ContainerVsMaterialStatus == CommonStatus.ENABLE).ToListAsync();

                        //组盘信息逻辑变更
                        var orderNo = YitIdHelper.NextId().ToString();

                        foreach (var materialItem in wareContainerVsMaterialList)
                        {
                            //删除入库时的组盘记录
                            materialItem.ContainerVsMaterialStatus = CommonStatus.DELETED;
                            await _wareContainerVsMaterialRep.UpdateAsync(materialItem);

                            ////新增停用出库时组盘记录
                            //var itemOut = new WareContainerVsMaterial()
                            //{
                            //    OrderNo = orderNo,
                            //    ContainerVsMaterialStatus = CommonStatus.DISABLE,
                            //    ProjectCode = materialItem.ProjectCode,
                            //    ContainerId = materialItem.ContainerId,
                            //    ContainerCode = item.ContainerCode,
                            //    MaterialId = materialItem.MaterialId,
                            //    BrandName = materialItem.BrandName,
                            //    XuHao = materialItem.XuHao,
                            //    Code = materialItem.Code,
                            //    Name = materialItem.Name,
                            //    SpecificationModel = materialItem.SpecificationModel,
                            //    Unit = materialItem.Unit,
                            //    InspectionMethod = materialItem.InspectionMethod,
                            //    BindQuantity = materialItem.BindQuantity,
                            //    SupplerCode = materialItem.SupplerCode
                            //};
                            //_wareContainerVsMaterialRep.InsertNow(itemOut);

                            ////新增 正常组盘记录
                            //var newitem = new WareContainerVsMaterial()
                            //{
                            //    OrderNo = YitIdHelper.NextId().ToString(),
                            //    ContainerVsMaterialStatus = CommonStatus.ENABLE,
                            //    ProjectCode = materialItem.ProjectCode,
                            //    ContainerId = materialItem.ContainerId,
                            //    ContainerCode = materialItem.ContainerCode,
                            //    MaterialId = materialItem.MaterialId,
                            //    BrandName = materialItem.BrandName,
                            //    XuHao = materialItem.XuHao,
                            //    Code = materialItem.Code,
                            //    Name = materialItem.Name,
                            //    SpecificationModel = materialItem.SpecificationModel,
                            //    Unit = materialItem.Unit,
                            //    InspectionMethod = materialItem.InspectionMethod,
                            //    BindQuantity = materialItem.BindQuantity,
                            //    SupplerCode = materialItem.SupplerCode
                            //};
                            //await _wareContainerVsMaterialRep.InsertAsync(newitem);
                        }

                        //库存
                        var wareStockList = await _wareStockRep.Where(n => n.ContainerCode == item.ContainerCode
                        && n.LocationCode == item.LocationCode).ToListAsync();

                        //清除库存对应库位
                        //修改库存
                        foreach (var stock in wareStockList)
                        {
                            stock.LocationCode = "N/A";
                            stock.StockQuantity = 0;
                            stock.CurrentQuantity = 0;

                            await _wareStockRep.UpdateAsync(stock);
                        }

                        //新增任务
                        var taskModel = new WareTask()
                        {
                            OrderNo = orderNo,
                            TaskNo = YitIdHelper.NextId().ToString(),
                            TaskModel = TaskModel.SHOUDONG,
                            TaskType = TaskType.Out,
                            TaskStatus = TaskStatusEnum.Complete,
                            TaskName = TaskNameConst.TemporaryLocation_ManualOut,
                            Priority = 1,
                            ContainerCode = item.ContainerCode,
                            FromLocationCode = item.LocationCode,
                            ToLocationCode = "N/A",
                            UpdatedUserId = CurrentUserInfo.UserId,
                            UpdatedUserName = CurrentUserInfo.Name,
                            UpdatedTime = DateTimeOffset.Now
                        };
                        await _wareTaskRep.InsertAsync(taskModel);

                        //更改托盘
                        wareContainer.ContainerStatus = ContainerStatusEnum.kongxian;
                        await _wareContainerRep.UpdateAsync(wareContainer);

                        //更新库位
                        locationModel.LocationStatus = LocationStatusEnum.kongxian;
                        locationModel.IsEmptyContainer = YesOrNot.N;
                        locationModel.Attribute = "小";
                        await _wareLocationRep.UpdateAsync(locationModel);

                        //删除托盘库位关系
                        wareLocationVsContainer.LocationVsContainerStatus = CommonStatus.DELETED;
                        await _wareLocationVsContainerRep.UpdateAsync(wareLocationVsContainer);
                    }

                    // 提交事务
                    scope.Complete();
                }
                catch (Exception ex)
                {
                    throw Oops.Oh("[TemporaryLocationIn]临时入库异常：" + ex.StackTrace + "," + ex.Message);
                }
                finally
                {
                    scope.Dispose();
                }
            }
        }

        /// <summary>
        /// 根据条件查询所属库区列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("AreaList")]
        public async Task<List<WareArea>> AreaList([FromQuery] AreaListInput input)
        {
            return await _wareAreaRep.DetachedEntities
                .Where(z => z.AreaType == AreaTypeEnum.XN).ToListAsync();
        }
    }
}
